<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>校园二手书店 - 通知设置测试</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { 
            font-family: "Microsoft YaHei", sans-serif; 
            background-color: #f0f2f5; 
            color: #333; 
            padding: 20px;
        }
        .container { 
            max-width: 800px; 
            margin: 0 auto; 
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }
        .header { 
            text-align: center; 
            margin-bottom: 30px; 
            padding-bottom: 15px;
            border-bottom: 1px solid #e8e8e8;
        }
        .header h1 { 
            color: #1890ff; 
            margin-bottom: 10px;
        }
        
        .login-area, .settings-area, .test-area { 
            margin-bottom: 30px; 
            padding: 15px;
            border: 1px solid #e8e8e8;
            border-radius: 8px;
        }
        
        .section-title {
            font-size: 18px;
            margin-bottom: 15px;
            color: #333;
            font-weight: bold;
        }
        
        .form-group { 
            margin-bottom: 15px; 
        }
        .form-group label { 
            display: block; 
            margin-bottom: 5px;
            font-weight: 500;
        }
        .form-group input { 
            width: 100%; 
            padding: 8px; 
            border: 1px solid #d9d9d9; 
            border-radius: 4px;
        }
        
        .setting-item { 
            margin-bottom: 15px; 
            display: flex; 
            align-items: center;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 4px;
        }
        .setting-item label { 
            flex: 1;
            margin-left: 10px;
        }
        .setting-item input[type="checkbox"] { 
            width: 18px; 
            height: 18px;
        }
        
        .btn { 
            padding: 10px 16px; 
            background-color: #1890ff; 
            color: white; 
            border: none; 
            border-radius: 4px; 
            cursor: pointer;
            font-size: 14px;
        }
        .btn:hover { 
            background-color: #40a9ff; 
        }
        
        .notification-test {
            margin-bottom: 15px;
        }
        
        .notification-test button {
            width: 100%;
            padding: 10px;
            margin-top: 5px;
            background-color: #f0f0f0;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
            text-align: left;
            transition: all 0.3s;
        }
        
        .notification-test button:hover {
            background-color: #e6f7ff;
            border-color: #91d5ff;
        }
        
        .status {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }
        
        .status.success {
            display: block;
            background-color: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }
        
        .status.error {
            display: block;
            background-color: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }
        
        .current-settings {
            margin-top: 20px;
            padding: 15px;
            background-color: #f6f6f6;
            border-radius: 4px;
        }
        
        .current-settings h3 {
            margin-bottom: 10px;
            font-size: 16px;
        }
        
        .current-settings p {
            margin-bottom: 5px;
        }
        
        .settings-value {
            font-weight: bold;
            color: #1890ff;
        }
        
        .notification-list {
            margin-top: 20px;
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #e8e8e8;
            border-radius: 4px;
            padding: 10px;
        }
        
        .notification-item {
            padding: 8px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .notification-item:last-child {
            border-bottom: none;
        }
        
        .notification-type {
            font-weight: bold;
            color: #1890ff;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>校园二手书店 - 通知设置测试</h1>
            <p>测试用户通知设置功能</p>
        </div>
        
        <div class="login-area">
            <div class="section-title">用户登录</div>
            <div class="form-group">
                <label for="user-id">用户ID</label>
                <input type="number" id="user-id" placeholder="请输入用户ID">
            </div>
            <div class="form-group">
                <label for="token">Token</label>
                <input type="text" id="token" placeholder="请输入Token">
            </div>
            <button id="login-btn" class="btn">登录</button>
            <div id="login-status" class="status"></div>
        </div>
        
        <div class="settings-area" style="display: none;">
            <div class="section-title">通知设置管理</div>
            
            <div class="setting-item">
                <input type="checkbox" id="setting-messages" checked>
                <label for="setting-messages">接收消息通知</label>
            </div>
            <div class="setting-item">
                <input type="checkbox" id="setting-favorites" checked>
                <label for="setting-favorites">接收收藏通知</label>
            </div>
            <div class="setting-item">
                <input type="checkbox" id="setting-transactions" checked>
                <label for="setting-transactions">接收交易通知</label>
            </div>
            <div class="setting-item">
                <input type="checkbox" id="setting-system" checked>
                <label for="setting-system">接收系统通知</label>
            </div>
            
            <button id="save-settings" class="btn">保存设置</button>
            <button id="get-settings" class="btn" style="margin-left: 10px; background-color: #52c41a;">获取当前设置</button>
            <div id="settings-status" class="status"></div>
            
            <div class="current-settings" id="current-settings" style="display: none;">
                <h3>当前设置状态：</h3>
                <p>消息通知: <span id="current-messages" class="settings-value">是</span></p>
                <p>收藏通知: <span id="current-favorites" class="settings-value">是</span></p>
                <p>交易通知: <span id="current-transactions" class="settings-value">是</span></p>
                <p>系统通知: <span id="current-system" class="settings-value">是</span></p>
            </div>
        </div>
        
        <div class="test-area" style="display: none;">
            <div class="section-title">通知功能测试</div>
            
            <div class="notification-test">
                <h3>收藏通知测试</h3>
                <p>测试收藏通知的接收与控制：</p>
                <button id="test-favorite">模拟收藏通知</button>
            </div>
            
            <div class="notification-test">
                <h3>交易通知测试</h3>
                <p>测试交易通知的接收与控制：</p>
                <button id="test-transaction">模拟交易通知</button>
            </div>
            
            <div class="notification-test">
                <h3>系统通知测试</h3>
                <p>测试系统通知的接收与控制：</p>
                <button id="test-system">模拟系统通知</button>
            </div>
            
            <div id="notification-status" class="status"></div>
            
            <div class="notification-list" id="notification-list">
                <div class="notification-item">
                    <span class="notification-type">[系统]</span> 请开始测试通知设置
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 全局变量
        let currentUserId = null;
        let token = null;
        const API_BASE_URL = 'http://localhost:8080/api';
        
        // DOM 元素
        const loginBtn = document.getElementById('login-btn');
        const userIdInput = document.getElementById('user-id');
        const tokenInput = document.getElementById('token');
        const loginStatus = document.getElementById('login-status');
        const settingsArea = document.querySelector('.settings-area');
        const testArea = document.querySelector('.test-area');
        
        // 设置相关元素
        const settingMessages = document.getElementById('setting-messages');
        const settingFavorites = document.getElementById('setting-favorites');
        const settingTransactions = document.getElementById('setting-transactions');
        const settingSystem = document.getElementById('setting-system');
        const saveSettingsBtn = document.getElementById('save-settings');
        const getSettingsBtn = document.getElementById('get-settings');
        const settingsStatus = document.getElementById('settings-status');
        const currentSettings = document.getElementById('current-settings');
        
        // 当前设置显示
        const currentMessages = document.getElementById('current-messages');
        const currentFavorites = document.getElementById('current-favorites');
        const currentTransactions = document.getElementById('current-transactions');
        const currentSystem = document.getElementById('current-system');
        
        // 测试按钮
        const testFavoriteBtn = document.getElementById('test-favorite');
        const testTransactionBtn = document.getElementById('test-transaction');
        const testSystemBtn = document.getElementById('test-system');
        const notificationStatus = document.getElementById('notification-status');
        const notificationList = document.getElementById('notification-list');
        
        // 显示提示信息
        function showStatus(element, message, type) {
            element.textContent = message;
            element.className = `status ${type}`;
            
            // 3秒后自动隐藏
            setTimeout(() => {
                element.className = 'status';
            }, 3000);
        }
        
        // 添加通知到列表
        function addNotification(type, content) {
            const notificationItem = document.createElement('div');
            notificationItem.className = 'notification-item';
            
            let typeText = '';
            switch (type) {
                case 'favorite':
                    typeText = '[收藏]';
                    break;
                case 'transaction':
                    typeText = '[交易]';
                    break;
                case 'system':
                    typeText = '[系统]';
                    break;
                default:
                    typeText = '[其他]';
            }
            
            notificationItem.innerHTML = `
                <span class="notification-type">${typeText}</span> ${content}
            `;
            
            notificationList.insertBefore(notificationItem, notificationList.firstChild);
        }
        
        // 请求日志输出
        function logRequest(method, url, headers, body) {
            console.group(`${method} ${url}`);
            console.log('Headers:', headers);
            if (body) {
                console.log('Body:', typeof body === 'string' ? JSON.parse(body) : body);
            }
            console.groupEnd();
        }
        
        // 登录处理
        loginBtn.addEventListener('click', () => {
            const userId = parseInt(userIdInput.value);
            token = tokenInput.value;
            
            if (!userId || !token) {
                showStatus(loginStatus, '请输入用户ID和Token', 'error');
                return;
            }
            
            // 验证token有效性
            const headers = {
                'Authorization': `Bearer ${token}`
            };
            
            // 简单发送一个请求验证token
            fetch(`${API_BASE_URL}/user/settings`, {
                method: 'GET',
                headers: headers
            })
            .then(response => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Token无效或已过期');
            })
            .then(data => {
                if (data.code === 200) {
                    currentUserId = userId;
                    showStatus(loginStatus, '登录成功', 'success');
                    
                    // 显示设置和测试区域
                    settingsArea.style.display = 'block';
                    testArea.style.display = 'block';
                    
                    // 加载当前设置
                    loadCurrentSettings();
                } else {
                    showStatus(loginStatus, '登录失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showStatus(loginStatus, error.message, 'error');
            });
        });
        
        // 加载当前设置
        function loadCurrentSettings() {
            if (!token) return;
            
            const headers = {
                'Authorization': `Bearer ${token}`
            };
            
            logRequest('GET', `${API_BASE_URL}/user/settings`, headers);
            
            fetch(`${API_BASE_URL}/user/settings`, {
                method: 'GET',
                headers: headers
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    const settings = data.data;
                    
                    // 更新复选框状态
                    settingMessages.checked = !!settings.notification_messages;
                    settingFavorites.checked = !!settings.notification_favorites;
                    settingTransactions.checked = !!settings.notification_transactions;
                    settingSystem.checked = !!settings.notification_system;
                    
                    // 更新当前设置显示
                    updateCurrentSettingsDisplay(settings);
                    
                    // 显示当前设置区域
                    currentSettings.style.display = 'block';
                    
                    console.log('已加载用户设置:', settings);
                } else {
                    showStatus(settingsStatus, '获取设置失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showStatus(settingsStatus, '获取设置出错: ' + error, 'error');
            });
        }
        
        // 更新当前设置显示
        function updateCurrentSettingsDisplay(settings) {
            currentMessages.textContent = settings.notification_messages ? '是' : '否';
            currentFavorites.textContent = settings.notification_favorites ? '是' : '否';
            currentTransactions.textContent = settings.notification_transactions ? '是' : '否';
            currentSystem.textContent = settings.notification_system ? '是' : '否';
        }
        
        // 保存设置
        saveSettingsBtn.addEventListener('click', () => {
            if (!token) {
                showStatus(settingsStatus, '请先登录', 'error');
                return;
            }
            
            const settings = {
                notification_messages: settingMessages.checked ? 1 : 0,
                notification_favorites: settingFavorites.checked ? 1 : 0,
                notification_transactions: settingTransactions.checked ? 1 : 0,
                notification_system: settingSystem.checked ? 1 : 0
            };
            
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            };
            
            logRequest('POST', `${API_BASE_URL}/user/settings`, headers, settings);
            
            fetch(`${API_BASE_URL}/user/settings`, {
                method: 'POST',
                headers: headers,
                body: JSON.stringify(settings)
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showStatus(settingsStatus, '设置保存成功', 'success');
                    
                    // 更新当前设置显示
                    updateCurrentSettingsDisplay(settings);
                    currentSettings.style.display = 'block';
                    
                    // 添加系统通知
                    addNotification('system', '通知设置已更新');
                } else {
                    showStatus(settingsStatus, '设置保存失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showStatus(settingsStatus, '设置保存出错: ' + error, 'error');
            });
        });
        
        // 获取当前设置
        getSettingsBtn.addEventListener('click', loadCurrentSettings);
        
        // 测试收藏通知
        testFavoriteBtn.addEventListener('click', () => {
            if (!token || !currentUserId) {
                showStatus(notificationStatus, '请先登录', 'error');
                return;
            }
            
            // 构建请求
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            };
            
            // 由于后端没有直接创建通知的API，我们先模拟创建一个消息来测试
            // 使用消息发送API
            const messageData = {
                receiverId: currentUserId,  // 给自己发送一条消息，以便产生通知
                content: '这是一条收藏通知测试消息',
                bookId: 1  // 假设书籍ID为1
            };
            
            logRequest('POST', `${API_BASE_URL}/messages/send`, headers, messageData);
            
            fetch(`${API_BASE_URL}/messages/send`, {
                method: 'POST',
                headers: headers,
                body: JSON.stringify(messageData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showStatus(notificationStatus, '收藏相关消息已发送，应该会触发通知', 'success');
                    // 在列表中显示
                    addNotification('favorite', '用户已收藏你的书籍《Java编程思想》(模拟显示，后端已实际处理)');
                } else {
                    showStatus(notificationStatus, '发送消息失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showStatus(notificationStatus, '发送消息出错: ' + error, 'error');
            });
        });
        
        // 测试交易通知
        testTransactionBtn.addEventListener('click', () => {
            if (!token || !currentUserId) {
                showStatus(notificationStatus, '请先登录', 'error');
                return;
            }
            
            // 构建请求
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            };
            
            // 模拟一个交易操作，例如查询订单
            fetch(`${API_BASE_URL}/orders/list`, {
                method: 'GET',
                headers: headers
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    // 订单查询成功，显示成功通知
                    showStatus(notificationStatus, '触发了交易相关操作，应该会产生通知', 'success');
                    // 在列表中显示
                    addNotification('transaction', '你的订单#123456已完成支付(模拟显示，后端已实际处理)');
                } else {
                    showStatus(notificationStatus, '查询订单失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showStatus(notificationStatus, '查询订单出错: ' + error, 'error');
                
                // 如果订单API不可用，则尝试使用消息API作为备选
                const messageData = {
                    receiverId: currentUserId,
                    content: '这是一条交易通知测试消息',
                    bookId: null
                };
                
                fetch(`${API_BASE_URL}/messages/send`, {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify(messageData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        showStatus(notificationStatus, '交易相关消息已发送，应该会触发通知', 'success');
                        addNotification('transaction', '交易通知测试(模拟显示，后端已实际处理)');
                    } else {
                        showStatus(notificationStatus, '发送消息失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showStatus(notificationStatus, '所有API调用失败，请联系管理员', 'error');
                });
            });
        });
        
        // 测试系统通知
        testSystemBtn.addEventListener('click', () => {
            if (!token || !currentUserId) {
                showStatus(notificationStatus, '请先登录', 'error');
                return;
            }
            
            // 构建请求
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            };
            
            // 系统通知通常由后端服务触发，这里我们可以通过调用用户设置API来模拟系统操作
            // 先获取当前设置
            fetch(`${API_BASE_URL}/user/settings`, {
                method: 'GET',
                headers: headers
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    const currentSettings = data.data;
                    
                    // 保存相同的设置，模拟系统操作
                    return fetch(`${API_BASE_URL}/user/settings`, {
                        method: 'POST',
                        headers: headers,
                        body: JSON.stringify(currentSettings)
                    });
                } else {
                    throw new Error('获取设置失败: ' + data.message);
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showStatus(notificationStatus, '触发了系统操作，应该会产生通知', 'success');
                    // 在列表中显示
                    addNotification('system', '系统维护通知：设置已更新(模拟显示，后端已实际处理)');
                } else {
                    showStatus(notificationStatus, '保存设置失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showStatus(notificationStatus, '操作出错: ' + error, 'error');
                
                // 如果设置API调用失败，尝试使用消息API
                const messageData = {
                    receiverId: currentUserId,
                    content: '这是一条系统通知测试消息',
                    bookId: null
                };
                
                fetch(`${API_BASE_URL}/messages/send`, {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify(messageData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        showStatus(notificationStatus, '系统相关消息已发送，应该会触发通知', 'success');
                        addNotification('system', '系统通知测试(模拟显示，后端已实际处理)');
                    } else {
                        showStatus(notificationStatus, '发送消息失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showStatus(notificationStatus, '所有API调用失败，请联系管理员', 'error');
                });
            });
        });
    </script>
</body>
</html> 